In [1]:
# import plotting libraries
%matplotlib inline
import matplotlib.pyplot as plt
Write a function that returns a list of numbers, such that $x_i=i^2$, for $1\leq i \leq n$. Make sure it handles the case where $n<1$ by raising a ValueError
.
In [2]:
def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
if n < 1:
raise ValueError("n must be greater than or equal to 1")
return [i ** 2 for i in xrange(1, n + 1)]
Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for $n=10$. Check that it does:
In [3]:
squares(10)
Out[3]:
In [4]:
In [4]:
Using your squares
function, write a function that computes the sum of the squares of the numbers from 1 to $n$. Your function should call the squares
function -- it should NOT reimplement its functionality.
In [4]:
def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
return sum(squares(n))
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:
In [5]:
sum_of_squares(10)
Out[5]:
In [6]:
In [6]:
Using LaTeX math notation, write out the equation that is implemented by your sum_of_squares
function.
$\sum_{i=1}^n i^2$
Create a plot of the sum of squares for $n=1$ to $n=15$. Make sure to appropriately label the $x$-axis and $y$-axis, and to give the plot a title. Set the $x$-axis limits to be 1 (minimum) and 15 (maximum).
In [6]:
fig, ax = plt.subplots() # do not delete this line!
x = range(1, 16)
y = [sum_of_squares(x[i]) for i in xrange(len(x))]
ax.plot(x, y)
ax.set_title("Sum of squares from 1 to $n$")
ax.set_xlabel("$n$")
ax.set_ylabel("sum")
ax.set_xlim([1, 15])
Out[6]:
In [7]:
In [7]:
In [7]:
In [7]:
In [7]:
In [7]: